<template>
  <div class="mapbox-maps">
    <div id="map">
      <div class="drew">
        <el-tooltip content="电子围栏检测" placement="bottom" popper-class="testtooltip">
          <el-tag
            @click="fenceDetection"
            :type="index == 0 ? '' : 'info'"
            :effect="index === 0 ? 'dark' : 'plain'"
          >
            <svg class="icon" aria-hidden="true" style="font-size: 16px; color: blue">
              <use xlink:href="#icon-point3"></use>
            </svg>
          </el-tag>
        </el-tooltip>
        <el-tooltip content="详情信息" placement="bottom" popper-class="testtooltip">
          <el-tag
            @click="viewMessage"
            :type="index == 0 ? '' : 'info'"
            :effect="index === 1 ? 'dark' : 'plain'"
          >
            <svg class="icon" aria-hidden="true" style="font-size: 16px">
              <use xlink:href="#icon-Point"></use>
            </svg>
          </el-tag>
        </el-tooltip>
      </div>

      <div id="handle" v-show="imshow">
        <i
          class="el-icon-arrow-right"
          @click="isShow"
          style="color: #67c23a; font-size: 25px"
        ></i>
      </div>
    </div>

    <el-drawer
      title="参数设置"
      :visible.sync="drawer"
      :before-close="handleClose"
      :modal="false"
      :modal-append-to-body="false"
      direction="rtl"
      custom-class="demo-drawer"
      ref="drawer"
    >
      <div
        class="demo-drawer__content"
        style="padding: 10px; height: 100%; position: relative"
      >
        <el-form :label-position="labelPosition" label-width="80px" :model="fenceForm">
          <el-form-item label="围栏名称">
            <el-input v-model="fenceForm.fenceName"></el-input>
          </el-form-item>
          <el-form-item label="图层标识">
            <el-input v-model="fenceForm.layerId"></el-input>
          </el-form-item>
          <el-form-item label="经度">
            <el-input v-model="fenceForm.longitude"></el-input>
          </el-form-item>
          <el-form-item label="纬度">
            <el-input v-model="fenceForm.latitude"></el-input>
          </el-form-item>
          <el-form-item label="选择文件">
            <el-upload
              class="upload"
              ref="upload"
              action="string"
              :file-list="fileList"
              :auto-upload="false"
              :http-request="uploadFile"
              :on-change="handleChange"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              multiple="multiple"
            >
              <el-button slot="trigger" size="small" type="primary" @click="delFile"
                >选取文件</el-button
              >
            </el-upload>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="fenceForm.remarks"></el-input>
          </el-form-item>
        </el-form>
        <div
          class="demo-drawer__footer"
          style="
            width: 100%;
            position: absolute;
            left: 0px;
            bottom: 0px;
            display: flex;
            justify-content: center;
          "
        >
          <el-button style="width: 150px" @click="cancelForm">取 消</el-button>
          <el-button style="width: 150px" type="primary" @click="submit">确定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import MapPop from "./MapPop";
import Vue from "vue";
import mapboxgl from "mapbox-gl";
// import MapboxLanguage  from '@mapbox/mapbox-gl-language'
export default {
  name: "ElectronicFenceShow",
  data() {
    return {
      index: 1,
      mapMarkers: [], //地图标记集合
      marker: {},
      map: {},
      imshow: false,
      drawer: false,
      fileList: [],
      multiple: false,
      fenceForm: {
        layerId: "",
        coordinates: [],
        fenceName: "",
        longitude: "",
        latitude: "",
        remarks: "",
      },
      geojson: {
        type: "geojson",
        data: {
          type: "FeatureCollection",
          features: [],
        },
      },
      json_polygon: {
        type: "FeatureCollection",
        features: [],
      }, //绘制面，添加面样式
      layerArray: new Array(),
      formLabelWidth: "80px",
      labelPosition: "right",
      timer: null,
      popupTemp: "",
      popup: {},
    };
  },
  beforeDestroy() {
    //离开页面，销毁地图实例
    this.map.remove();
    console.log(this.map);
  },
  mounted() {
    this.loadMap();
  },

  methods: {
    loadMap() {
      let that = this;
      // 英文标注转换为中文
      // mapboxgl.setRTLTextPlugin('https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.1.0/mapbox-gl-rtl-text.js');
      this.map = new mapboxgl.Map({
        accessToken:
          "pk.eyJ1Ijoienh0d24iLCJhIjoiY2wzanV3bHduMTZwejNrcXcyd3B1bzBieiJ9.aW_TDqLomftwPvBu7OWqwQ",
        container: "map",
        style: "mapbox://styles/mapbox/satellite-streets-v10", //https://www.iotword.com/2082.html
        center: [116.779398421, 32.694871269], // starting position [lng, lat]
        zoom: 12, // starting zoom
        hash: false,
        pitch: 45, //地图的角度，不写默认是0，取值是0-60度，一般在3D中使用
        bearing: 0, //地图的初始方向，值是北的逆时针度数，默认是0，即是正北
        antialias: true, //抗锯齿，通过false关闭提升性能
        projection: "globe",
      });
      // 设置语言
      // var language = new MapboxLanguage({ defaultLanguage: "zh" });
      // this.map.addControl(language);
      // mapboxgl.setRTLTextPlugin('https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.1.0/mapbox-gl-rtl-text.js');
      // this.map.addControl(new MapboxLanguage({defaultLanguage: 'zh-Hans'}));
      that.map.getCanvas().style.cursor = "pointer";
      // 比例尺
      var scale = new mapboxgl.ScaleControl({
        maxWidth: 100,
        unit: "metric",
      });
      this.map.addControl(scale, "bottom-left");
      this.draw = new this.$mapboxdraw({
        displayControlsDefault: false,
        controls: {
          polygon: true,
          // line_string: true,
          // point: true,
          trash: true,
        },
      });
      this.map.addControl(this.draw);
      //地图导航
      var nav = new mapboxgl.NavigationControl();
      this.map.addControl(nav, "top-right");
      // 定位
      this.map.addControl(
        new mapboxgl.GeolocateControl({
          positionOptions: {
            enableHighAccuracy: true,
          },
          trackUserLocation: true,
        })
      );
      // 全图
      // this.map.addControl(new mapboxgl.FullscreenControl());
      this.map.on("draw.create", createLayer);
      this.map.on("draw.delete", deleteLayer);
      this.map.on("draw.update", updateLayer);
      this.map.on("load", function () {
        that.map.setFog({
          color: "rgb(186, 210, 235)",
          "high-color": "rgb(36, 92, 223)",
          "horizon-blend": 0.02,
          "space-color": "rgb(11, 11, 25)",
          "star-intensity": 0.6,
        });

        that.map.addSource("drew_polygon", {
          type: "geojson",
          data: that.json_polygon,
        });
        that.map.addLayer({
          id: "drew_polygon",
          type: "fill",
          source: "drew_polygon",
          paint: {
            "fill-color": "#FF5511 ",
            "fill-opacity": 0.3,
          },
        });
        that.map.addLayer({
          id: "electronic_fence_title",
          type: "symbol",
          source: "drew_polygon",
          layout: {
            visibility: "visible",
            "text-field": "{fenceName}",
            "text-size": 14,
          },
          paint: {
            "text-halo-color": "#00FF00",
            //'text-halo-width': 2
          },
        });
        that.map.addLayer({
          id: "pointlayerhighlight",
          type: "fill",
          source: "drew_polygon",
          paint: {
            "fill-color": "#228B22 ",
            "fill-opacity": 0.3,
          },
          filter: ["in", "fenceName", ""],
        });

        that.map.addLayer({
          id: "pointlayerhighlights",
          type: "fill",
          source: "drew_polygon",
          paint: {
            "fill-color": "#FFFF00 ",
            "fill-opacity": 0.3,
          },
          filter: ["in", "fenceName", ""],
        });
        that.popup = new mapboxgl.Popup({
          // closeButton: false,
          closeOnClick: false,
        });
        that.loadLayerAll();
      });

      /**
       * 创建图层
       */
      function createLayer(e) {
        that.fenceForm.coordinates = [];
        that.fenceForm.coordinates = e.features;
        that.fenceForm.layerId = e.features[0].id;
        let centroid = that.$turf.centroid(e.features[0]);
        that.fenceForm.longitude = centroid.geometry.coordinates[0];
        that.fenceForm.latitude = centroid.geometry.coordinates[1];
        that.drawer = !that.drawer;
        that.imshow = false;
        console.log(centroid);
        console.log("create" + e);
      }
      function deleteLayer(e) {
        that.fenceForm.coordinates = [];
        that.fenceForm.layerId = "";
        that.fenceForm.longitude = "";
        that.fenceForm.latitude = "";
        that.imshow = false;
        console.log("delete" + e);
      }
      function updateLayer(e) {
        that.fenceForm.coordinates = [];
        that.fenceForm.coordinates = e.features;
        that.fenceForm.layerId = e.features[0].id;
        let centroid = that.$turf.centroid(e.features[0]);
        that.fenceForm.longitude = centroid.geometry.coordinates[0];
        that.fenceForm.latitude = centroid.geometry.coordinates[1];
        that.drawer = !that.drawer;
        that.imshow = true;
        console.log("update" + e);
      }
    },
    /**
     * 添加图标
     */
    fenceDetection() {
      let that = this;
      that.index = 1;
      if (that.popup.isOpen()) that.popup.remove();
      that.map.off("click", "drew_polygon", that.clickViewMessage);
      that.map.getCanvas().style.cursor = "crosshair";
      // 禁止双击缩放
      that.map.doubleClickZoom.disable();
      that.map.on("click", that.clickEvent);

      // that.map.off('click',clickEvent)
      // function
    },
    viewMessage() {
      let that = this;
      that.index = 1;
      that.map.off("click", that.clickEvent);
      that.map.on("click", "drew_polygon", that.clickViewMessage);
    },
    clickViewMessage(e) {
      let that = this;
      that.mapMarkers.forEach((marker) => marker.remove());
      that.mapMarkers = [];
      var feature = e.features[0];
      that.map.setFilter("pointlayerhighlight", [
        "in",
        "fenceName",
        feature.properties.fenceName,
      ]);
      that.details(e);
      console.log(e);
    },
    clickEvent(_e) {
      let that = this;
      let intersectOrContain = false;
      // eslint-disable-next-line no-unused-vars
      let fenceName = "";
      var pt = this.$turf.point([_e.lngLat.lng, _e.lngLat.lat]);
      for (let index in that.json_polygon.features) {
        intersectOrContain = that.$turf.booleanPointInPolygon(
          pt,
          that.json_polygon.features[index]
        );
        if (intersectOrContain) {
          that.map.setFilter("pointlayerhighlight", [
            "in",
            "fenceName",
            that.json_polygon.features[index].properties.fenceName,
          ]);
          fenceName = that.json_polygon.features[index].properties.fenceName;
          break;
        }
      }
      var starCoords = [];
      starCoords = [];
      starCoords.push(_e.lngLat.lat);
      starCoords.unshift(_e.lngLat.lng);
      that.marker = new mapboxgl.Marker().setLngLat(starCoords).addTo(that.map);
      that.mapMarkers.forEach((marker) => marker.remove());
      that.mapMarkers = [];
      that.mapMarkers.push(that.marker);
      if (!intersectOrContain) {
        // that.$message("这是一条消息提示");
      } else {
        that.$message({
          message: `警告！有一条记录进入--${fenceName}--围栏内`,
          type: "warning",
        });
      }
    },
    /**
     * 详情信息
     *
     */
    details(e) {
      console.log(e);
      let _this = this;
      this.popupTemp = "";
      /**
       * 创建map地图弹框组件
       *
       */
      const p = Vue.extend(MapPop);
      let vm = new p({
        propsData: {
          objes: {
            map: _this.map,
            layerId: e.features[0].properties.layerId,
            fenceName: e.features[0].properties.fenceName,
            longitude: e.features[0].properties.longitude,
            latitude: e.features[0].properties.latitude,
            remarks: e.features[0].properties.remarks,
            that: _this,
          },
        }, //传参
      });

      vm.$mount(); //挂载
      _this.popupTemp = vm.$el;
      if (_this.popup) {
        _this.popup.remove();
      }
      // 添加信息框
      _this.popup
        .setLngLat(new mapboxgl.LngLat(e.lngLat.lng, e.lngLat.lat))
        .setDOMContent(vm.$el) //插入节点
        .addTo(_this.map);
    },
    handleClose() {
      this.drawer = !this.drawer;
      this.imshow = true;
    },
    /**
     * 抽屉控制
     */
    isShow() {
      this.drawer = !this.drawer;
    },
    cancelForm() {},
    /**
     * 提交
     */
    submit() {
      let that = this;
      let formData = new FormData();
      formData.append("file", that.fileList[0].raw);
      formData.append("layerId", that.fenceForm.layerId);
      formData.append("coordinates", JSON.stringify(that.fenceForm.coordinates));
      formData.append("fenceName", that.fenceForm.fenceName);
      formData.append("longitude", that.fenceForm.longitude);
      formData.append("latitude", that.fenceForm.latitude);
      formData.append("remarks", that.fenceForm.remarks);
      that.$axios
        .post("http://localhost:9002/fence/newAdd", formData, {
          "Content-Type": "multipart/form-data;charset=utf-8",
        })
        .then(function (res) {
          console.log(res);
          that.drawer = !that.drawer;
          window.location.reload();
        })
        .catch(function (error) {
          console.log(error);
        });
      // that.$axios
      //   .post("http://localhost:9002/fence/add", {
      //     layerId: that.fenceForm.layerId,
      //     coordinates: JSON.stringify(that.fenceForm.coordinates),
      //     fenceName: that.fenceForm.fenceName,
      //     longitude: that.fenceForm.longitude,
      //     latitude: that.fenceForm.latitude,
      //     remarks: that.fenceForm.remarks,
      //   })
      //   .then(function (res) {
      //     console.log(res);
      //     that.drawer = !that.drawer;
      //     window.location.reload();
      //   })
      //   .catch(function (error) {
      //     console.log(error);
      //   });
    },
    //点击上传文件触发的额外事件,清空fileList
    delFile() {
      this.fileList = [];
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
      // console.log(this.fileList, "sb");
    },
    //自定义上传文件
    uploadFile(file) {
      // this.formData.append("file", file.file);
      console.log(file.file, "sb2");
    },
    //删除文件
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 点击文件
    handlePreview(file) {
      console.log(file);
    },
    loadLayerAll() {
      let that = this;
      that.$axios
        .post("http://localhost:9002/fence/select/all", {})
        .then(function (res) {
          console.log(res);
          //遍历显示图层
          that.json_polygon.features = [];
          that.map.getSource("drew_polygon").setData(that.json_polygon);
          res.data.data.forEach((e) => {
            if (e.coordinates != null) {
              let features = JSON.parse(e.coordinates);
              features[0].properties["fenceName"] = e.fenceName;
              features[0].properties["layerId"] = e.layerId;
              features[0].properties["longitude"] = e.longitude;
              features[0].properties["latitude"] = e.latitude;
              features[0].properties["remarks"] = e.remarks;
              that.json_polygon.features.push(features[0]);
            }
          });
          that.map.getSource("drew_polygon").setData(that.json_polygon);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
  },
};
</script>
<style scoped lang="scss">
@import "https://api.mapbox.com/mapbox-gl-js/v2.3.0/mapbox-gl.css";
.icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
.mapbox-maps {
  width: 100%;
  height: calc(100vh - 50px);
  position: relative;
}
#map {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
.mapboxgl-canvas {
  outline: none;
}
/* 隐藏mapbox商标 */
.mapboxgl-ctrl-logo {
  display: none;
}

.drew {
  // width: 316px;
  height: 34px;
  border-radius: 0px;
  z-index: 4;
  position: absolute;
  left: 10px;
  top: 10px;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  background: rgba(255, 255, 255, 0.8);
  box-shadow: 0 0 0 2pxrgba 0, 0, 0, 0.1;
}

//修改文字提示样式
.el-tooltip__popper[x-placement^="bottom"] .popper__arrow {
  border-bottom-color: rgba(148, 147, 147, 0.877) !important;
}
.el-tooltip__popper[x-placement^="bottom"] .popper__arrow:after {
  border-bottom-color: rgba(148, 147, 147, 0.877) !important;
}
.testtooltip {
  background: rgba(148, 147, 147, 0.877) !important;
  box-shadow: 1px 1px 10px 3px #d3d3d6;
}
//修改地图比例尺样式
.mapboxgl-ctrl.mapboxgl-ctrl-scale {
  height: 10px;
  background-color: transparent;
  line-height: 10%;
  text-align: center;
}

#handle {
  position: absolute;
  left: 0px;
  top: 50%;
  z-index: 4;
  border: 1px solid #67c23a;
}
</style>
